package com.sihai.ehr.jdbc;

import com.sihai.ehr.web.pojo.LeaveType;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * author: wxn
 * since: 13-10-14 下午9:34
 * 出差，外出
 */
public class QingJiaService {
    private static String startTime;
    private static String endTime;

    private Connection connection;

    public void connection()throws Exception{
        connection = JDBCHelper.connection();
        if(connection == null){
            throw new IllegalArgumentException("jdbc连接失败");
        }
    }

    public void close()throws Exception{
        if(connection != null && !connection.isClosed()){
            JDBCHelper.close(connection);
        }
    }

    private final static int ONE_DAY_TIME = 24 * 60 * 60 * 1000; //一天对应的毫秒数
    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
    private static int startHour;
    private static int startMinute;
    private static int endHour;
    private static int endMinute;
    public int insert(QingJia qingJia)throws Exception{
        if(qingJia != null && qingJia.getUser_serial() > 0){
            if(StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)){
                Properties properties = PropertiesLoaderUtils.loadAllProperties("jdbc.properties");
                startTime = properties.getProperty("kj_start_time", "08:00");
                endTime = properties.getProperty("kj_end_time", "17:00");
            }

            Date date = timeFormat.parse(startTime);
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            startHour = c.get(Calendar.HOUR_OF_DAY);
            startMinute = c.get(Calendar.MINUTE);
            date = timeFormat.parse(endTime);
            c.setTime(date);
            endHour = c.get(Calendar.HOUR_OF_DAY);
            endMinute = c.get(Calendar.MINUTE);
            System.out.println(String.format("开始小时：%s, 分钟：%s, 结束小时：%s, 分钟：%s", startHour, startMinute, endHour, endMinute));


            Date startDate = qingJia.getKssj();
            Date endDate = qingJia.getJssj();

            List<QingJia> list = new ArrayList<QingJia>();
            //如果两个日期不在同一天
            if(!DateUtils.isSameDay(startDate, endDate)){
                long times = Math.abs(endDate.getTime() - startDate.getTime());
                int n = (int)(times % ONE_DAY_TIME == 0 ? times/ONE_DAY_TIME : times/ONE_DAY_TIME + 1);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startDate);
                int h1 = calendar.get(Calendar.HOUR_OF_DAY); //起始时间的小时数
                calendar.setTime(endDate);
                int h2 = calendar.get(Calendar.HOUR_OF_DAY); //结束时间的小时数
                if(h2 <= h1){
                    n++;
                }
                System.out.println("两个时间段共经历天数:"+n);
                for(int i=0; i<n; i++){
                    QingJia qj = new QingJia();
                    BeanUtils.copyProperties(qingJia, qj);
                    qj.setKssj(startDate);
                    //如果是最后一项，则设置结束时间为选择的时间，否则为开始时间当天的指定小时和分钟
                    if(i == n-1){
                        qj.setJssj(endDate);
                    }else{
                        calendar.setTime(startDate);
                        calendar.set(Calendar.HOUR, endHour);
                        calendar.set(Calendar.MINUTE, endMinute);
                        qj.setJssj(calendar.getTime());
                    }

                    calendar.setTime(startDate);
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    calendar.set(Calendar.HOUR, startHour);
                    calendar.set(Calendar.MINUTE, startMinute);
                    startDate = calendar.getTime();

                    list.add(qj);
                }
            }else{
                list.add(qingJia);
            }

            for(QingJia qj : list){
                //bh kssj jssj jsjg bz gly_no shenhe lx jbrq
                PreparedStatement pst = connection.prepareStatement("insert into lr_waich values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                pst.setInt(1, qj.getUser_serial());
                pst.setString(2, qj.getBh());
                pst.setString(3, DateUtil.formatDate(qj.getKssj(), "yyyy-MM-dd HH:mm"));
                pst.setString(4, DateUtil.formatDate(qj.getJssj(), "yyyy-MM-dd HH:mm"));
                pst.setInt(5, qj.getMinutes()); //总计分钟
                pst.setString(6, qj.getBz());
                pst.setString(7, "admin");
                pst.setString(8, "admin");
                pst.setInt(9, 0);
                pst.setString(10, DateUtil.formatDate(qj.getKssj(), "yyyy-MM-dd HH:mm"));
                int row = pst.executeUpdate();
                if(row > 0){
                    System.out.println("添加请假、外出成功***********************");
                }else{
                    System.out.println("添加请假、外出失败***********************");
                }
            }
            return 1;
        }

        return 0;
    }

    //查找请假类别
    public List<LeaveType> findAllLeaveType()throws Exception{
        try{
            PreparedStatement pst = connection.prepareStatement("select * from kt_qingj");
            ResultSet rs = pst.executeQuery();
            List<LeaveType> list = new ArrayList<LeaveType>();
            while (rs.next()) {
                LeaveType leaveType = new LeaveType();
                leaveType.setTypeCode(rs.getString("bh"));
                leaveType.setTypeName(rs.getString("mc"));
                list.add(leaveType);
            }

            return list;
        }catch(SQLException e) {
            e.printStackTrace();
        }

        return null;
    }
}
